package ejb;

import datamodel.Category;
import datamodel.SystemAdmin;
import datamodel.SystemCustomer;
import datamodel.Ticket;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class TicketManager {

    @PersistenceContext
    private EntityManager em;

    @RolesAllowed({"SystemAdmin", "System"})
    public List<Ticket> getAllTickets() {
        return em.createQuery("SELECT t FROM Ticket t").getResultList();
    }
    
    @RolesAllowed({"SystemCustomer"})
    public List<Ticket> getCustomerTickets(SystemCustomer u) {
        return em.createQuery("SELECT t FROM Ticket t WHERE t.createdBy=:user").setParameter("user", u).getResultList();
    }

    @RolesAllowed({"SystemAdmin"})
    public List<Ticket> getAdminSolvingTickets(SystemAdmin u) {
        return em.createQuery("SELECT t FROM Ticket t WHERE t.solvedBy=:user").setParameter("user", u).getResultList();
    }
    
    @RolesAllowed({"SystemAdmin"})
    public List<Ticket> getAdminAvailableTickets(SystemAdmin u) {
        return em.createQuery("SELECT t FROM Ticket t WHERE t.category IN (SELECT c.id FROM SystemUser s LEFT JOIN s.canSolve c WHERE s.id=:user)"
                + " UNION SELECT t FROM Post p LEFT JOIN p.inTicket t WHERE p.wroteBy=:user").setParameter("user", u.getId()).getResultList();
    }

    @RolesAllowed({"SystemCustomer"})
    public void saveTicket(Ticket temp) {
        em.persist(temp);
        System.out.println("saving ticket!");
        em.flush();
    }

    @RolesAllowed({"SystemAdmin","SystemCustomer"})
    public Ticket getTicket(long id) {
        return em.find(Ticket.class, id);
    }
   
    @RolesAllowed({"SystemAdmin"})
    public void remove(Ticket temp){
        em.remove(temp);
        em.flush();
    }
    
    @RolesAllowed({"SystemAdmin","SystemCustomer"})
    public void update(Ticket t){
        em.merge(t);
    }
}
